package com.school.sports.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.sports.dto.ProjectDTO;
import com.school.sports.entity.Project;
import com.school.sports.mapper.ProjectMapper;
import com.school.sports.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 运动项目服务实现类
 */
@Slf4j
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Override
    @Cacheable(value = "projects", key = "'project:' + #id", unless = "#result == null")
    public Project getProjectWithCreator(Long id) {
        // 调用mapper的关联查询方法
        return baseMapper.selectProjectWithCreator(id);
    }

    @Override
    @CacheEvict(value = "projects", allEntries = true)
    public boolean updateProjectStatus(Long id, String status) {
        // 校验项目是否存在
        Project project = baseMapper.selectById(id);
        if (project == null) {
            return false;
        }
        // 更新状态和更新时间
        project.setStatus(status);
        project.setUpdatedAt(LocalDateTime.now());
        return baseMapper.updateById(project) > 0;
    }

    @Override
    public boolean existsByName(String name) {
        // 校验项目名称是否已存在
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getName, name)
                .eq(Project::getDeleted, 0);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public IPage<Project> page(Page<Project> page, LambdaQueryWrapper<Project> queryWrapper) {
        // 确保只查询未删除的项目
        queryWrapper.eq(Project::getDeleted, 0);
        // 调用mybatis-plus的分页查询
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Cacheable(value = "projects", key = "'type:' + #type", unless = "#result == null || #result.isEmpty()")
    public List<Project> getProjectsByType(String type) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getType, type)
                .eq(Project::getDeleted, 0)
                .orderByDesc(Project::getCreatedAt);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Cacheable(value = "projects", key = "'status:' + #status", unless = "#result == null || #result.isEmpty()")
    public List<Project> getProjectsByStatus(String status) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getStatus, status)
                .eq(Project::getDeleted, 0)
                .orderByDesc(Project::getCreatedAt);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<String> getAllProjectTypes() {
        return Arrays.asList("径赛", "田赛", "球类", "其他");
    }

    @Override
    public List<String> getAllProjectStatuses() {
        return Arrays.asList("未开始", "报名中", "进行中", "已结束", "已取消");
    }

    @Override
    public List<String> getAllGenderLimits() {
        return Arrays.asList("男", "女", "无");
    }

    @Override
    @CacheEvict(value = "projects", allEntries = true)
    public boolean batchUpdateStatus(List<Long> projectIds, String status) {
        try {
            for (Long projectId : projectIds) {
                updateProjectStatus(projectId, status);
            }
            return true;
        } catch (Exception e) {
            log.error("批量更新项目状态失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public long countProjects() {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getDeleted, 0);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public long countProjectsByStatus(String status) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getStatus, status)
                .eq(Project::getDeleted, 0);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    @Cacheable(value = "projects", key = "'popular:' + #limit", unless = "#result == null || #result.isEmpty()")
    public List<Project> getPopularProjects(Integer limit) {
        // 这里暂时按创建时间倒序返回，实际项目中应该按报名人数排序
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getDeleted, 0)
                .orderByDesc(Project::getCreatedAt);

        if (limit != null && limit > 0) {
            queryWrapper.last("LIMIT " + limit);
        }

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<ProjectDTO> getProjectPageWithDetails(Page<ProjectDTO> page, String name, String type, String status, String genderLimit) {
        // 使用优化的JOIN查询，避免N+1问题
        return baseMapper.selectProjectPageWithDetails(page, name, type, status, genderLimit);
    }

    @Override
    @Cacheable(value = "projects", key = "'details:' + #projectId", unless = "#result == null")
    public ProjectDTO getProjectDetailsById(Long projectId) {
        // 使用优化的JOIN查询，避免N+1问题
        return baseMapper.selectProjectByIdWithDetails(projectId);
    }

    @Override
    @Cacheable(value = "projects", key = "'search:' + #name", unless = "#result == null || #result.isEmpty()")
    public List<ProjectDTO> searchProjectsByName(String name) {
        // 使用优化的索引查询
        return baseMapper.selectProjectsByNameLike(name);
    }

    @Override
    @Cacheable(value = "projects", key = "'available'", unless = "#result == null || #result.isEmpty()")
    public List<ProjectDTO> getAvailableProjects() {
        // 使用优化的JOIN查询，避免N+1问题
        return baseMapper.selectAvailableProjects();
    }
}